package com.example.weight.greenSeasons.deodorization;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class DuifeiDeodorization_old extends AppCompatActivity implements View.OnClickListener{
    private TitleBar titleBar;
    //下拉框
    private ExpandableLayout expand_1;
    private Button textView1;
    private ExpandableLayout expand_2;
    private Button textView2;
    private TextView dateEdit;
    //用户、抄表人
    private String name, role, factory;
//各类时间
    EditText dosing_time, dosing_time2, add_water_time, add_water_time2, huzuiguanlu_clean_time, huzuiguanlu_clean_time2,tianliao_clean_time, tianliao_clean_time2, tianliao_replace_time, tianliao_replace_time2,find_problems_time,
        drug_name, drug_name2, drug_usage, drug_usage2, is_water_enough, is_water_enough2, huzuiguanlu_clean_description, huzuiguanlu_clean_description2, operator, remarks;
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duifei_deodorization_table_old);
        drug_name = (EditText) findViewById(R.id.drug_name);
        drug_name2 = (EditText) findViewById(R.id.drug_name2);
        drug_usage = (EditText) findViewById(R.id.drug_usage);
        drug_usage2 = (EditText) findViewById(R.id.drug_usage2);
        is_water_enough = (EditText) findViewById(R.id.is_water_enough);
        is_water_enough2 = (EditText) findViewById(R.id.is_water_enough2);
        huzuiguanlu_clean_description = (EditText) findViewById(R.id.huzuiguanlu_clean_description);
        huzuiguanlu_clean_description2 = (EditText) findViewById(R.id.huzuiguanlu_clean_description2);
        remarks = (EditText) findViewById(R.id.remarks);
        //用户和职责
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        factory = previousIntent.getStringExtra("factory");

        operator=findViewById(R.id.operator);
        operator.setText(name);
        operator.setFocusableInTouchMode(false);

        //下拉框
        expand_1=findViewById(R.id.expandable_1);
        textView1=findViewById(R.id.button_1);

        expand_2=findViewById(R.id.expandable_2);
        textView2=findViewById(R.id.button_2);
//        加药时间
        dosing_time = (EditText) findViewById(R.id.dosing_time);
        dosing_time.setOnClickListener(this);
        dosing_time2 = (EditText) findViewById(R.id.dosing_time2);
        dosing_time2.setOnClickListener(this);
//        加水时间
        add_water_time = (EditText) findViewById(R.id.add_water_time);
        add_water_time.setOnClickListener(this);
        add_water_time2 = (EditText) findViewById(R.id.add_water_time2);
        add_water_time2.setOnClickListener(this);
//        壶嘴管路清洗时间
        huzuiguanlu_clean_time = (EditText) findViewById(R.id.huzuiguanlu_clean_time);
        huzuiguanlu_clean_time.setOnClickListener(this);
        huzuiguanlu_clean_time2 = (EditText) findViewById(R.id.huzuiguanlu_clean_time2);
        huzuiguanlu_clean_time2.setOnClickListener(this);
//        填料清洗时间
        tianliao_clean_time = (EditText) findViewById(R.id.tianliao_clean_time);
        tianliao_clean_time.setOnClickListener(this);
        tianliao_clean_time2 = (EditText) findViewById(R.id.tianliao_clean_time2);
        tianliao_clean_time2.setOnClickListener(this);
//        填料更换时间
        tianliao_replace_time = (EditText) findViewById(R.id.tianliao_replace_time);
        tianliao_replace_time.setOnClickListener(this);
        tianliao_replace_time2 = (EditText) findViewById(R.id.tianliao_replace_time2);
        tianliao_replace_time2.setOnClickListener(this);
//        发现并反映问题时间
        find_problems_time = (EditText) findViewById(R.id.find_problems_time);
        find_problems_time.setOnClickListener(this);
//        日期
        dateEdit=findViewById(R.id.compost_editDate);
//        Calendar calendar=Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        Integer day = calendar.get(calendar.DAY_OF_MONTH);
        dateEdit.setText(year+"-"+month+"-"+day);
        //标题返回按钮
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                DuifeiDeodorization_old.this.finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });
        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/SjqDeodorizationRunningTwo/getLast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (!data.isNull("id")) {
                                dosing_time.setText(data.getString("dosingTime1"));
                                add_water_time.setText(data.getString("waterTime1"));
                                drug_name.setText(data.getString("drugName1"));
                                drug_usage.setText(data.getString("dosage1"));
                                is_water_enough.setText(data.getString("isScaleMark1"));
                                huzuiguanlu_clean_time.setText(data.getString("nozzlePipelineCleanTime1"));
                                huzuiguanlu_clean_description.setText(data.getString("nozzlePipelineCleanCondition1"));
                                tianliao_clean_time.setText(data.getString("packingCleaningTime1"));
                                tianliao_replace_time.setText(data.getString("packingReplacementTime1"));
                                dosing_time2.setText(data.getString("dosingTime2"));
                                add_water_time2.setText(data.getString("waterTime2"));
                                drug_name2.setText(data.getString("drugName2"));
                                drug_usage2.setText(data.getString("dosage2"));
                                is_water_enough2.setText(data.getString("isScaleMark2"));
                                huzuiguanlu_clean_time2.setText(data.getString("nozzlePipelineCleanTime2"));
                                huzuiguanlu_clean_description2.setText(data.getString("nozzlePipelineCleanCondition2"));
                                tianliao_clean_time2.setText(data.getString("packingCleaningTime2"));
                                tianliao_replace_time2.setText(data.getString("packingReplacementTime2"));
                                find_problems_time.setText(data.getString("reportTime"));
                                operator.setText(data.getString("operator"));
                                remarks.setText(data.getString("remarks"));
                                Toast.makeText(DuifeiDeodorization_old.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DuifeiDeodorization_old.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_water_time:
                chooseStopDate(this,  add_water_time);
                break;
            case R.id.dosing_time:
                chooseStopDate(this,  dosing_time);
                break;
            case R.id.add_water_time2:
                chooseStopDate(this,  add_water_time2);
                break;
            case R.id.dosing_time2:
                chooseStopDate(this,  dosing_time2);
                break;
            case R.id.huzuiguanlu_clean_time:
                chooseStopDate(this,  huzuiguanlu_clean_time);
                break;
            case R.id.huzuiguanlu_clean_time2:
                chooseStopDate(this,  huzuiguanlu_clean_time2);
                break;
            case R.id.tianliao_clean_time:
                chooseStopDate(this,  tianliao_clean_time);
                break;
            case R.id.tianliao_clean_time2:
                chooseStopDate(this,  tianliao_clean_time2);
                break;
            case R.id.tianliao_replace_time:
                chooseStopDate(this,  tianliao_replace_time);
                break;
            case R.id.tianliao_replace_time2:
                chooseStopDate(this,  tianliao_replace_time2);
                break;
            case R.id.find_problems_time:
                chooseStopDate(this,  find_problems_time);
                break;
            default:  
                break;
        }
    }

    /**
     * 提交内容并设置输入缓存
     * @param view
     */
    public void save(View view) {
        if (dosing_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔加药时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (dosing_time2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔加药时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (add_water_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔加水时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (add_water_time2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔加水时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (huzuiguanlu_clean_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔壶嘴，管路清洁时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (huzuiguanlu_clean_time2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔壶嘴，管路清洁时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tianliao_clean_time2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔填料清洁时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tianliao_clean_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔填料清洁时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tianliao_replace_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔填料更换时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tianliao_replace_time2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔填料更换时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (find_problems_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写发现问题并反映给技术部时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (drug_name.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔药剂名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (drug_name2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔药剂名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (drug_usage.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔药剂使用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (drug_usage2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔药剂使用量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (is_water_enough.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔加水量是否到规定刻度线", Toast.LENGTH_SHORT).show();
            return;
        }
        if (is_water_enough2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔加水量是否到规定刻度线", Toast.LENGTH_SHORT).show();
            return;
        }
        if (huzuiguanlu_clean_description.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1#除臭塔壶嘴，管路清洗情况", Toast.LENGTH_SHORT).show();
            return;
        }
        if (huzuiguanlu_clean_description2.getText().toString().equals("")) {
            Toast.makeText(this, "请填写2#除臭塔壶嘴，管路清洗情况", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/SjqDeodorizationRunningTwo/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Toast.makeText(DuifeiDeodorization_old.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(DuifeiDeodorization_old.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(DuifeiDeodorization_old.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(DuifeiDeodorization_old.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("dosingTime1", dosing_time.getText().toString());
                            map.put("waterTime1", add_water_time.getText().toString());
                            map.put("drugName1", drug_name.getText().toString());
                            map.put("dosage1", drug_usage.getText().toString());
                            map.put("isScaleMark1", is_water_enough.getText().toString());
                            map.put("nozzlePipelineCleanTime1", huzuiguanlu_clean_time.getText().toString());
                            map.put("nozzlePipelineCleanCondition1", huzuiguanlu_clean_description.getText().toString());
                            map.put("packingCleaningTime1", tianliao_clean_time.getText().toString());
                            map.put("packingReplacementTime1", tianliao_replace_time.getText().toString());
                            map.put("dosingTime2", dosing_time2.getText().toString());
                            map.put("waterTime2", add_water_time2.getText().toString());
                            map.put("drugName2", drug_name2.getText().toString());
                            map.put("dosage2", drug_usage2.getText().toString());
                            map.put("isScaleMark2", is_water_enough2.getText().toString());
                            map.put("nozzlePipelineCleanTime2", huzuiguanlu_clean_time2.getText().toString());
                            map.put("nozzlePipelineCleanCondition2", huzuiguanlu_clean_description2.getText().toString());
                            map.put("packingCleaningTime2", tianliao_clean_time2.getText().toString());
                            map.put("packingReplacementTime2", tianliao_replace_time2.getText().toString());
                            map.put("reportTime", find_problems_time.getText().toString());
                            map.put("operator", operator.getText().toString());
                            map.put("remarks", remarks.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
    public void show1(View view) {
        if (expand_1.isExpanded()){
            textView1.setText("+ 1#除臭塔（南侧）");
        }else{
            textView1.setText("- 1#除臭塔（南侧）");
        }
        expand_1.toggle();
    }

    public void show2(View view) {
        if (expand_2.isExpanded()){
            textView2.setText("+ 2#除臭塔（北侧）");
        }else{
            textView2.setText("- 2#除臭塔（北侧）");
        }
        expand_2.toggle();
    }
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void chooseStopDate(Activity activity,final TextView tv) {

        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                tv.setText(new StringBuilder()
                        .append(year)
                        .append("/")
                        .append((month + 1) < 10 ? "0"
                                + (month + 1) : (month + 1))
                        .append("/")
                        .append((day < 10) ? "0" + day : day)
                        .append(" ")
                        .append(String.format("%02d",hourOfDay))
                        .append(":")
                        .append(String.format("%02d",minute)));
            },
                    HOUR, MINUTE, true).show();
        },
                YEAR, MONTH, DAY).show();
    }
    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    @SuppressLint("ResourceType")
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity,int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.AM_PM)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }
}
